package cn.nubia.admin.sysconfig.service;

import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.sysconfig.bean.SysConfig;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2015/6/26.
 */
@Service
public class SysConfigService  extends BaseServiceImpl<SysConfig>{

    private static Map<String, String> sysConfig = new ConcurrentHashMap<>();

    @Autowired
    SystemLogService systemLogService;

    /**
     * 获取网页配置
     */
    public  Map<String, String> getSystemConfigMap() {
        if (sysConfig.isEmpty()) {
            setSystemConfigMap();
        }
        return sysConfig;
    }


    public Map<String,String> getSystemConfig(){
        Query<SysConfig> query = Query.build(SysConfig.class);
        query.addEq("isSystem",SysConfig.IS_SYSTEM);
        List<SysConfig> webConfigs = findByQuery(query);
        for (SysConfig config : webConfigs) {
            sysConfig.put(config.getName(), config.getValue());
        }
        return sysConfig;
    }

    /**
     * 保存网页静态配置
     */
    public  void setSystemConfigMap() {

        Query<SysConfig> query = Query.build(SysConfig.class);
        query.addEq("isSystem",SysConfig.IS_SYSTEM);
        List<SysConfig> webConfigs = findByQuery(query);
        for (SysConfig config : webConfigs) {
            sysConfig.put(config.getName(), config.getValue());
        }
    }

    /**
     * 系统配置.
     * 适用于修改网页配置时调用
     */
    public synchronized static void clearWebConfig() {
        sysConfig.clear();
    }

    public void saveSysConfigMap(Map<String, String> map) {
        for (String s : map.keySet()) {
            Query<SysConfig>query = Query.build(SysConfig.class);
            query.addEq("isSystem",SysConfig.IS_SYSTEM);
            query.addEq("name",s);
            SysConfig sysConfig = get(query);
            if(sysConfig!=null){
                sysConfig.setValue(map.get(s));
                sysConfig.setUpdateTime(new Date());
                update(sysConfig);
                systemLogService.log(SystemLog.ModuleTypeEnum.SYSCONFIGLIST, SystemLog.OperateTypeEnum.EDIT, sysConfig.getId());
                clearWebConfig();
            }

        }

    }
}
